<template>
  <div>
    <!-- 面包屑导航区-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <el-row>
        <el-col><el-button type="primary">添加用户</el-button></el-col>
      </el-row>
      <!-- 表格区-->
      <el-table :data="rolesTableData" border>
        <el-table-column type="expand"  width="80">
            <template slot-scope="scope">
                <el-row v-for="(item1,index1) in scope.row.children" :key="item1.id" :class="['bb',index1 === 0 ? 'bt':'','center']">
                    <!-- -->
                    <!-- 渲染一级权限-->
                    <el-col :span="5">
                        <el-tag closable @close="deleteRight(scope.row,scope.row.id,item1.id)">{{item1.authName}}</el-tag>
                        <i class="el-icon-caret-right"></i>
                    </el-col>
                    <el-col :span="19">
                        <!-- 渲染二级和三级权限-->
                        <el-row  v-for="(item2,index2) in item1.children" :key="item2.id" :class="[ index2 === 0? '':'bt','center']">
                            <el-col :span="6" >
                                <el-tag closable @close="deleteRight(scope.row,scope.row.id,item2.id)" type="success">{{item2.authName}}</el-tag>
                                <i class="el-icon-caret-right"></i>
                            </el-col>
                            <el-col :span="18">
                                <el-tag closable @close="deleteRight(scope.row,scope.row.id,item3.id)" type="warning" v-for="item3 in item2.children" :key="item3.id">{{item3.authName}}</el-tag>
                            </el-col>
                        </el-row>
                    </el-col>
                </el-row>
            </template>
        </el-table-column>
        <el-table-column type="index" label="#" width="180"></el-table-column>
        <el-table-column
          prop="roleName"
          label="角色名称"
          width="180"
        ></el-table-column>
        <el-table-column
          prop="roleDesc"
          label="角色描述"
          width="180"
        ></el-table-column>
        <el-table-column label="操作" width="380">
          <template slot-scope="scope">
            <el-button type="primary"  icon="el-icon-edit" size="mini" >编辑</el-button>
            <el-button type="danger" icon="el-icon-delete"  size="mini">删除</el-button>
            <el-button  type="warning"  icon="el-icon-star-off" size="mini" @click="setRight(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分配权限的对话框-->
    <el-dialog @close="setRightDialogClose" title="分配权限" :visible.sync="setRightdialogVisible"  width="50%" >
        <el-tree ref="treeRef" :data="setTreedata" show-checkbox node-key="id" :default-checked-keys="defKeys" default-expand-all :props="defaultTreeProps" ></el-tree>
        <span slot="footer" >
            <el-button @click="setRightdialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="setRolesRight" >确 定</el-button>
        </span>
    </el-dialog>
  </div>
</template>

<script type="text/ecmascript-6">
import {requestRolesData,requestDeleteRolesRight,requestRolesTreeData,requestRolesRight} from "@/network/power/roles.js"
export default {
data() {
   return {
        //角色表格数据
        rolesTableData:[],
        //控制树形控件的显示与隐藏变量
        setRightdialogVisible:false,
        //树形控件展示的数据
        setTreedata:[],
        defaultTreeProps:{
            children:'children',
            label: 'authName'
        },
        //默认选中节点的ID数组
        defKeys:[],
        //当前选中角色授权的角色ID
        roleId:''
    }
},
created() {
        this.getRolesData()
},
methods: {
    //通过递归，获取三级权限的所有ID，并保存到defKeys中
    getDefId(node, arr){
        if(!node.children){
            return arr.push(node.id)
        }
        node.children.forEach(item =>
            this.getDefId(item,arr)
        )
    },
    //分配权限的对话框关闭后，要重置defKeys中的数据
    setRightDialogClose(){
        this.defKeys = []
    },



   //发送网络请求，获取数据
   async getRolesData(){
       const {data} = await requestRolesData()
       this.rolesTableData = data.data
   },
   //发送网络请求，删除对应的权限
   async deleteRight(row,roleId,rightId){
       const res = await this.$confirm('此操作将会删除该权限, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
        // console.log(res);
        if(res === 'confirm'){
            const {data} = await requestDeleteRolesRight({url:`roles/${roleId}/rights/${rightId}`})
            if(data.meta.status !== 200) return this.$message.error('删除权限失败')
            row.children = data.data
            // console.log(row);
            this.$message.success('删除权限成功')
        }
       
   },
   //分配权限的网络请求
   async setRight(rowData){
        this.roleId = rowData.id
        const {data} = await requestRolesTreeData()
        if(data.meta.status !== 200) return this.$message.error('获取权限数据失败')
        this.setTreedata = data.data
        this.getDefId(rowData,this.defKeys)
        this.setRightdialogVisible = true
   },
   //角色授权的网络请求
   async setRolesRight(){
        const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
        const idStr = keys.join(',')
        const {data} = await requestRolesRight({url:`roles/${this.roleId}/rights`,data:{ rids: idStr }})
        
        if(data.meta.status !== 200) return this.$message.error('角色分配权限分配失败')
        this.$message.success("分配权限成功")
        this.setRightdialogVisible = false
        this.getRolesData()
        
   }
},
}
</script>

<style lang="less" scoped>
    
    .el-tag{
        margin: 5px;
        
    }
    .bb{
        border-bottom: 1px solid #ccc;
    }
    .bt{
        border-top: 1px solid #ccc;
    }
    .center{
        display: flex;
        align-items: center;
    }

</style>
